import React, { useState, useEffect } from 'react';
import { useNavigate } from 'react-router-dom';
import { ArrowLeftOutlined, PlusOutlined } from '@ant-design/icons';
import { Button, Modal, Input, message as AntMessage, List, Card, Tag, Image, Pagination, Typography, Empty } from 'antd';
import { http, API_PATH } from '../utils/http';
import type { PaginationMeta } from '../utils/http';

const { Text, Paragraph } = Typography;

// Interfaces for the image task list
interface TaskResultItem {
    type: string;
    index: number;
    url: string;
}

interface ImageTaskItem {
    id: string;
    article_id: string | null;
    article_text: string | null;
    article_type: string;
    status: string; // This seems to be a general status, task_status is more specific for the generation task
    created_at: number;
    updated_at: number;
    img_desc: string | null;
    img_url: string | null; // Potential fallback or alternative image URL
    img_index: number | null;
    task_id: string | null;
    task_status: string | null;
    task_status_msg: string | null;
    task_result: TaskResultItem[] | null;
    error: string | null;
}

// Define CreateImageTaskData if it was removed or ensure it is present for the modal
interface CreateImageTaskData {
    task_id: string;
    created_at: number;
}

const IllustrationCenter: React.FC = () => {
    const navigate = useNavigate();
    const [isModalOpen, setIsModalOpen] = useState(false);
    const [textValue, setTextValue] = useState('');
    const [isCreatingTask, setIsCreatingTask] = useState(false);

    // State for the list
    const [tasks, setTasks] = useState<ImageTaskItem[]>([]);
    const [isLoadingList, setIsLoadingList] = useState(false);
    const [pagination, setPagination] = useState<PaginationMeta>({
        page: 1,
        page_size: 10,
        total: 0,
        total_pages: 0,
        has_more: false,
    });

    // Fetch image tasks function
    const fetchImageTasks = async (currentPage = pagination.page, currentPageSize = pagination.page_size) => {
        setIsLoadingList(true);
        try {
            const response = await http.get<ImageTaskItem>(
                API_PATH.ILLUSTRATION.GET_IMAGE_TASKS,
                { page: currentPage, page_size: currentPageSize }
            );
            response.onSuccess(() => {
                setTasks(response.list || []); // Ensure list is always an array
                if (response.meta) {
                    setPagination({
                        page: response.meta.page,
                        page_size: response.meta.page_size,
                        total: response.meta.total,
                        total_pages: response.meta.total_pages,
                        has_more: response.meta.has_more,
                    });
                } else {
                    // If no meta, assume it's a non-paginated list or handle accordingly
                    const totalItems = response.list?.length || 0;
                    const calculatedTotalPages = Math.ceil(totalItems / currentPageSize);
                    setPagination(prev => ({
                        ...prev,
                        page: currentPage,
                        page_size: currentPageSize,
                        total: totalItems,
                        total_pages: calculatedTotalPages,
                        has_more: currentPage < calculatedTotalPages,
                    }));
                }
            }).onError((code, msg) => {
                AntMessage.error(`获取任务列表失败: ${msg} (错误码: ${code})`);
            });
        } catch (error: unknown) {
            console.error('获取任务列表失败:', error);
            AntMessage.error('获取任务列表失败，请稍后重试');
        } finally {
            setIsLoadingList(false);
        }
    };

    // useEffect to load tasks on mount and when pagination changes
    useEffect(() => {
        fetchImageTasks();
    }, []); // Fetch on mount. Pagination changes will be handled by onTableChange

    const handleBack = () => {
        window.location.href = '/';
    };

    const showModal = () => {
        setIsModalOpen(true);
    };

    const handleOkCreateTask = async () => {
        if (!textValue.trim()) {
            AntMessage.warning('请输入文本内容');
            return;
        }
        setIsCreatingTask(true);
        try {
            const response = await http.post<CreateImageTaskData>(
                API_PATH.ILLUSTRATION.CREATE_IMAGE_TASK,
                { text: textValue }
            );
            response.onSuccess(() => {
                if (response.data) {
                    AntMessage.success(`任务创建成功，任务ID: ${response.data.task_id}`);
                    setIsModalOpen(false);
                    setTextValue('');
                    fetchImageTasks(1, pagination.page_size); // Refresh list to show the new task, go to first page, keep page_size
                } else {
                    AntMessage.error(response.message || '任务创建成功，但未返回任务信息');
                }
            }).onError((code, msg) => {
                AntMessage.error(`任务创建失败: ${msg} (错误码: ${code})`);
            });
        } catch (error: unknown) {
            console.error('创建生图任务失败:', error);
            if (typeof error === 'object' && error !== null && 'message' in error) {
                const err = error as { message?: string };
                AntMessage.error(err.message || '网络请求或处理失败');
            } else if (error instanceof Error) {
                AntMessage.error(error.message || '网络请求异常');
            } else {
                AntMessage.error('发生未知错误');
            }
        } finally {
            setIsCreatingTask(false);
        }
    };

    const handleCancelCreateTask = () => {
        setIsModalOpen(false);
    };

    // Function to render status tag (reused from previous table logic)
    const renderStatusTag = (task_status: string | null, status: string) => {
        const currentStatus = task_status || status;
        let color = 'default';
        let displayText = currentStatus || '未知';
        switch (currentStatus?.toLowerCase()) {
            case 'succeed': color = 'green'; displayText = '成功'; break;
            case 'failed': color = 'red'; displayText = '失败'; break;
            case 'processing': color = 'blue'; displayText = '处理中'; break;
            case 'pending': color = 'gold'; displayText = '待执行'; break;
            case 'submitted': color = 'cyan'; displayText = '已提交'; break;
            default: if (!currentStatus) displayText = '未知'; break;
        }
        return <Tag color={color}>{displayText}</Tag>;
    };

    const handlePaginationChange = (page: number, pageSize?: number) => {
        fetchImageTasks(page, pageSize || pagination.page_size);
    };

    const handleCardClick = (taskId: string) => {
        navigate(`/illustration-task/${taskId}`);
    };

    return (
        <div className="min-h-screen bg-gray-50 p-6 sm:p-8">
            <div className="max-w-7xl mx-auto">
                <div className="mb-6 flex items-center justify-between">
                    <button
                        onClick={handleBack}
                        className="inline-flex items-center px-3 py-1.5 border border-gray-300 text-sm font-medium rounded-md text-gray-700 bg-white hover:bg-gray-50 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-indigo-500"
                    >
                        <ArrowLeftOutlined className="-ml-1 mr-2 h-5 w-5 text-gray-500" aria-hidden="true" />
                        返回首页
                    </button>
                    <h1 className="text-2xl font-semibold text-gray-900">配图中心</h1>
                    <Button
                        type="primary"
                        icon={<PlusOutlined />}
                        onClick={showModal}
                    >
                        创建生图任务
                    </Button>
                </div>

                {/* Main content area: Cards list */}
                <div className="bg-white shadow-sm rounded-lg p-6">
                    <List
                        grid={{ gutter: 16, xs: 1, sm: 2, md: 2, lg: 3, xl: 4, xxl: 4 }}
                        dataSource={tasks}
                        loading={isLoadingList}
                        locale={{ emptyText: <Empty description="暂无生图任务" /> }}
                        renderItem={(item: ImageTaskItem) => {
                            const imageUrl = item.task_result?.[0]?.url || item.img_url;
                            return (
                                <List.Item key={item.id} onClick={() => handleCardClick(item.id)} style={{ cursor: 'pointer' }}>
                                    <Card
                                        hoverable
                                        style={{ width: '100%' }}
                                        cover={
                                            imageUrl ? (
                                                <Image
                                                    alt={item.img_desc || '任务图片'}
                                                    src={imageUrl}
                                                    style={{ height: 200, objectFit: 'contain', padding: '8px' }} // contain to see full image, padding for aesthetics
                                                    preview // Enable preview
                                                />
                                            ) : (
                                                <div style={{ height: 200, display: 'flex', alignItems: 'center', justifyContent: 'center', background: '#f0f0f0' }}>
                                                    <Text type="secondary">无图片</Text>
                                                </div>
                                            )
                                        }
                                    >
                                        <Card.Meta
                                            title={<Paragraph ellipsis={{ rows: 1, tooltip: item.img_desc || '无描述' }}>{item.img_desc || '无描述'}</Paragraph>}
                                        />
                                        <div style={{ marginTop: 12 }}>
                                            <div style={{ marginBottom: 8 }}>
                                                <Text strong>状态: </Text>
                                                {renderStatusTag(item.task_status, item.status)}
                                            </div>
                                            <div style={{ marginBottom: 8 }}>
                                                <Text strong>创建时间: </Text>
                                                <Text>{new Date(item.created_at).toLocaleString()}</Text>
                                            </div>
                                            {item.task_id && (
                                                <div>
                                                    <Text strong>任务ID (AI): </Text>
                                                    <Text copyable={{ text: item.task_id }} ellipsis={{ tooltip: item.task_id }}>{item.task_id}</Text>
                                                </div>
                                            )}
                                        </div>
                                    </Card>
                                </List.Item>
                            );
                        }}
                    />
                    {tasks.length > 0 && (
                        <div style={{ marginTop: 24, textAlign: 'center' }}>
                            <Pagination
                                current={pagination.page}
                                pageSize={pagination.page_size}
                                total={pagination.total}
                                onChange={handlePaginationChange}
                                showSizeChanger
                                pageSizeOptions={['10', '20', '50']} // Example, adjust as needed
                            />
                        </div>
                    )}
                </div>
            </div>
            <Modal
                title="创建生图任务"
                open={isModalOpen}
                onOk={handleOkCreateTask}
                onCancel={handleCancelCreateTask}
                confirmLoading={isCreatingTask}
                okText="确定"
                cancelText="取消"
                destroyOnClose
            >
                <Input.TextArea
                    rows={6}
                    placeholder="请输入用于生成图片的文本描述，例如：一只可爱的猫咪在草地上玩耍，背景是蓝天白云。"
                    value={textValue}
                    onChange={(e) => setTextValue(e.target.value)}
                />
            </Modal>
        </div>
    );
};

export default IllustrationCenter; 